/**
 * Created by GadflyBSD on 14-7-16.
 */
define( function(require, exports, module) {
	var jQuery  = require('jquery');
	(function ($) {
		$.extend($, {
			Messenger: function(message){
				require.async('messenger', function(){
					Messenger().hideAll();
					Messenger().post({
						type: 'success',
						message: message
					});
				});
			},
			DialogComplete: function(SWFupload, numFilesSelected, numFilesQueued, totalNumFilesQueued){
				require.async('messenger', function(){
					var Mess = Messenger().post({
						message: '选择了'+numFilesSelected+'个文件，'+numFilesQueued+'个文件加入上传队列，上传队列中共有'+totalNumFilesQueued+'个文件',
						type: 'error',
						actions: {
							retry: {
								label: '上传',
								phrase: 'Retrying TIME',
								auto: true,
								delay: 10,
								action: function(){
									SWFupload.startUpload();
									Mess.hide()
								}
							},
							cancel: {
								label: "稍后上传",
								action: function(){
									Mess.cancel();
								}
							},
							delete: {
								label: "清除队列",
								action: function(){
									SWFupload.cancelQueue();
									Mess.hide();
								}
							}
						}
					});
				});
			},
			QueueComplete: function(numFilesUploaded){
				var message = numFilesUploaded + " file:" + (numFilesUploaded === 1 ? "" : "s") + " uploaded.";
				$.Messenger(message);
			},
			uploadStart: function(file){
				var message = file.name + '文件正在上传...';
				$.Messenger(message);
			}
		});
		$.extend($.fn, {
			seaSWFupload: function(options){
				var $this = $(this),
					config = {
					flash_url : seajs.data.base+"Upload/swfupload/swfupload.swf",
					flash9_url : seajs.data.base+"Upload/swfupload/swfupload_fp9.swf",
					upload_url: seajs.data.base+"Upload/swfupload/upload.php",
					css: "Upload/uploadify/uploadify.css",
					file_size_limit : "100 MB",
					file_types : "*.*",
					file_types_description : "All Files",
					file_upload_limit : 100,
					file_queue_limit : 0,
					debug: false,
					// Button Settings
					button_image_url : seajs.data.base+"Upload/swfupload/XPButtonNoText_61x22.png",
					button_placeholder_id : "spanButtonPlaceholder",
					button_width: 61,
					button_height: 22,
					button_text: '<span class="theFont">上传图片</span>',
					button_text_style: ".theFont { font-size: 12px; }",
					button_text_left_padding: 5,
					button_text_top_padding: 2,
					// The event handler functions are defined in handlers.js
					queueDom: 'div',
					swfupload_preload_handler : function(){
						if (!this.support.loading) {
							alert("您需要 Flash Player 版本高于 9.028 才能运行 SWFUpload！");
							return false;
						}
					},
					swfupload_load_failed_handler : function(){
						alert("当页面不能正常加载 SWFupload flash。可能是因为没有安装Flash Player或者它的版本低于 9.0.28！");
					},
					swfupload_loaded_handler : function(){},
					file_queued_handler : function(file){
						try {
							$('#tdFilesQueued').text(this.getStats().files_queued);
						} catch (ex) {
							this.debug(ex);
						}
					},
					file_queue_error_handler : function(){},
					file_dialog_complete_handler : function(numFilesSelected, numFilesQueued, totalNumFilesQueued){
						try {
							if (numFilesSelected > 0) {
								$.DialogComplete(this, numFilesSelected, numFilesQueued, totalNumFilesQueued);
							}
						} catch (ex)  {
							this.debug(ex);
						}
					},
					upload_start_handler : function(file) {
						try {
							$.uploadStart(file);
							this.customSettings.progressCount = 0;
							updateDisplay.call(this, file);
						}catch (ex) {
							this.debug(ex);
						}
					},
					upload_progress_handler : function(file, bytesLoaded, bytesTotal){
						//try {
						this.customSettings.progressCount++;
						updateDisplay.call(this, file);
						//} catch (ex) {
						//	this.debug(ex);
						//}
					},
					upload_error_handler : function(){},
					upload_success_handler : function(){},
					upload_complete_handler : function(file) {
						//$('#tdFilesQueued').text(this.getStats().files_queued);
						//$('#tdFilesUploaded').text(this.getStats().successful_uploads);
						//$('#tdErrors').text(this.getStats().upload_errors);
					},
					queue_complete_handler : function(numFilesUploaded) {
						$.QueueComplete(numFilesUploaded);
					}
				};
				$.seaBase.run(config, options, function(setting){
					if(!config.id) config.id = 'seaSWFupload_'+ $.seaBase.mathRand();
					$this.attr('id', config.id);
					config.button_placeholder_id = config.id;
					setting.upload_url = ($this.data('url'))?$this.data('url'):setting.upload_url;
					require.async('Upload/swfupload/swfupload', function(){
						//console.log(setting);
						SWFUpload.onload = function(){setting};
						var swfu = new SWFUpload(setting);
						var appendQueue = '<'+setting.queueDom+' class="'+swfu.movieName+'_Queue" \>';
						$('#'+swfu.movieName).parent('div').append(appendQueue);
						//console.log(swfu);
					});
				});
			},
			plupload: function(options){
				var $this = $(this),
					browse_id = ($this.attr('id'))?$this.attr('id'):'plupload_'+ $.seaBase.mathRand(),
					config = {
						runtimes : 'html5,flash,silverlight,html4',     //上传插件初始化选用那种方式的优先级顺序，如果第一个初始化失败就走第二个，依次类推
						browse_button : browse_id,   //触发浏览文件按钮标签的唯一id,,在flash、html5、和silverlight中能找到触发事件的源
						upload_after_hide_button: false,        //上传后隐藏上传按钮
						container: browse_id+'_container',    //展现上传文件列表的容器，[默认是body]
						filelist: browse_id+'_filelist',        //加载失败所显示的错误信息容器
						input_name: 'upload',
						siteurl: window.location.protocol+'//'+window.location.host,
						url : "upload.php",     //上传服务器地址
						unique_names: true, //是否生成唯一的文件名，避免与服务器文件重名
						file_data_name: 'file',  //设置上传字段的名称。默认情况下被设置为文件。
						flash_swf_url : '/Public/javascript/Upload/plupload/Moxie.swf', //flash文件地址
						silverlight_xap_url : '/Public/javascript/Upload/plupload/js/Moxie.xap',    // silverlight所在路径
						filters : {
							max_file_size : '10mb', //最大上传文件大小（格式100b, 10kb, 10mb, 1gb）
							mime_types: [
								{title : "Image files", extensions : "jpg,gif,png,bmp"},
								{title : "Zip files", extensions : "zip,arj,gz,rar,tar"}
							]
						},
						max_file_count: 20,
						chunk_size: '2mb',  //当上传文件大于服务器接收端文件大小限制的时候，可以分多次请求发给服务器，如果不需要从设置中移出
						multi_selection:true,  //是否支持多选
						views: {list: true, thumbs: true, active: 'thumbs'},
						//resize : {width : 200,height : 200,quality : 90,crop: true},    //修改图片属性
						is_reupload: false,
						init: {
							PostInit: function(up) {      //init执行完以后要执行的事件触发
								$('#'+up.settings.filelist).remove();
							},
							BeforeUpload: function(up, file){},     //文件上传完之前触发的事件
							ChunkUploaded: function(up, file,response){},  //文件被分块上传的事件
							Destroy: function(up){},    //uploader的destroy调用的方法
							Error: function(up, err){    //上传出错的时候触发
								if(up.settings.multi_selection) $('#'+up.settings.container).append('<li>\nError #'+err.code+':'+err.message+'</li>');
								else  $('#'+up.settings.container).append('\nError #'+err.code+':'+err.message);
							},
							FilesAdded: function(up, files){   //用户选择文件时触发
								if(up.settings.upload_after_hide_button) $(up.settings.browse_button).hide();
								up.start();
							},
							FileRemoved: function(up, files){},      //当文件从上传队列中移除触发
							FileUploaded: function(up, file, res){   //文件上传成功的时候触发
								console.log(up);
								var fileUrl = up.settings.siteurl+res.response,
									input_name = up.settings.input_name,
									container = $('#'+up.settings.container), multi = up.settings.multi_selection;
								if(multi){
									container.append('<li><div class="thumbImage"><a data-sea="ColorBox" href="'+fileUrl+'" class="thumbnail">' +
									                 '<img src="'+fileUrl+'" sea-toggle="centerImage"/></a></div>' +
									                 '<div class="uploadTextarea"><textarea name="'+input_name+'[summary][]" placeholder="请填写图片说明"></textarea>' +
									                 '<input type="text" name="'+input_name+'[title][]" value="'+file.name+'" />&nbsp'+
									                 '<input type="radio" name="'+input_name+'[isflag][]" checked="checked" value="1"><lable> 设为封面</lable></div><div>' +
									                 '<a href="javascript:voil(0);"class="delImg btn btn-danger btn-xs"><i class="icon-remove-2"></i></a></div>' +
									                 '<input type="hidden" name="'+input_name+'[url][]" value="'+res.response+'" /></li>');
								}else{
									if(config.is_reupload){
										$('#'+config.reuploadID).attr('href', fileUrl);
										$('#'+config.reuploadID).find('img').attr('src', fileUrl);
									}else{
										container.append('<a data-sea="ColorBox" href="'+fileUrl+'" class="thumbnail"><img src="'+fileUrl+'"/></a>' +
										                 '<a href="javascript:voil(0);" class="delImg btn btn-danger btn-xs"><i class="icon-remove-2"></i></a>');
									}
									container.next('input').val(res.response);
								}
								container.seaLoad();
								container.on('click', 'a.delImg', function(){
									var item = (multi)?$(this).closest('li'):container;
									if(confirm('真的要删除最近上传的【'+file.name+'】文件吗？')){
										item.empty();
										if(!multi) $('[name='+input_name+']').val('');
										$('#'+up.settings.browse_button).show();
									}
									return false;
								});
							},
							Init: function(up){},   //当初始化的时候触发
							QueueChanged: function(up){},   //当文件队列变化时触发
							Refresh: function(up){},     //当silverlight/flash或是其他运行环境需要移动的时候触发
							StateChanged: function(up){}, //当整个上传队列被改变的时候触发
							UploadComplete: function(up,file){},    //当队列中所有文件被上传完时触发
							UploadFile: function(up,file){},    //当一个文件被上传的时候触发
							UploadProgress: function(up, file) {}  //当文件正在被上传中触发
						}
					};
				$.seaBase.run(config, options, function(setting){
					$this.attr('id', setting.browse_button);
					$this.after('<div id="'+setting.filelist+'">您的浏览器不支持 Flash, Silverlight or HTML5 support.</div>');
					if(setting.multi_selection) $this.after('<ul id="'+setting.container+'" />');
					else $this.after('<div id="'+setting.container+'" />');
					require.async('Upload/plupload/plupload.full.min', function(){
						var uploader = new plupload.Uploader(setting);
						uploader.init();
					});
				});
			}
		});
	}(jQuery));
	return jQuery;
});